﻿using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.NetworkInformation;
using VideoMeetting.Base.DomainModel;

namespace VideoMeettingServer
{
    /// <summary>
    /// 房间管理器
    /// </summary>
    public static class RoomManager
    {
        private static List<MeettingRoom> _rooms;
        private static object _lockObj = new object();
        private static int _minPort = 10000;
        private static int _maxPort = 60000;
        private static string _udpAddress = ConfigurationManager.AppSettings["UdpAddress"];

        public static List<MeettingRoom> Rooms
        {
            get { return _rooms; }
            set { _rooms = value; }
        }

        static RoomManager()
        {
            Rooms = new List<MeettingRoom>();
        }

        public static MeettingRoom AddRoom()
        {
            try
            {
                lock (_lockObj)
                {
                    //获取端口
                    var port = GetFreePort();

                    if (port == -1) return null;

                    var room = new MeettingRoom { UdpPort = port, UdpAddress = _udpAddress, Title = $"测试房间{port}" };

                    if (Rooms.All(x => x.Id != room.Id))
                    {
                        Rooms.Add(room);

                        return room;
                    }

                    return null;
                }
            }
            catch (System.Exception ex)
            {
                return null;
            }
        }

        public static void RemoveRoom(string roomId)
        {
            lock (_lockObj)
            {
                var room = Rooms.FirstOrDefault(x => x.Id == roomId);

                if (room != null)
                {
                    Rooms.Remove(room);
                }
            }
        }

        /// <summary>
        /// 获取空闲的端口
        /// </summary>
        /// <returns></returns>
        private static int GetFreePort()
        {
            var allPort = GetAllPort();

            for (int i = _minPort; i <= _maxPort; i++)
            {
                if (allPort.All(x => x != i))
                {
                    return i;
                }
            }

            return -1;
        }

        /// <summary>
        /// 获取所有正在使用的端口
        /// </summary>
        /// <returns></returns>
        private static List<int> GetAllPort()
        {
            var allPort = new List<int>();

            var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();

            ipGlobalProperties.GetActiveTcpListeners().Select(x => x.Port).ToList().ForEach(x => { allPort.Add(x); });

            ipGlobalProperties.GetActiveUdpListeners().Select(x => x.Port).ToList().ForEach(x => { allPort.Add(x); });

            ipGlobalProperties.GetActiveTcpConnections().Select(x => x.LocalEndPoint.Port).ToList().ForEach(x => { allPort.Add(x); });

            return allPort;
        }
    }
}